/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.venda;

import bin.Item;
import bin.clientes.Cliente;
import gui.JanelaPrincipal;
import gui.clientes.JanelaPesquisaClientes;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Vinicius
 */
public class Pesquisa extends javax.swing.JDialog {

    private JanelaPrincipal janelaPrincipal;
    private String tipoPesquisa;
    
    /**
     * Atributo utilizado para armazenar o campo onde será colocado o ID do objeto selecionado.
     * <br>Será atribuido neste campo quando o usuário clicar no botão "Concluir" com algum
     * <br>registro selecionado na tebela.
     */
    private JTextField campoRegistroSelecionado;
    
    /**
     * Creates new form Pesquisa
     */
    public Pesquisa(java.awt.Frame parent, boolean modal, JanelaPrincipal janelaPrincipal,String objetoPesquisa, JTextField campoRegistroSelecionado) {
        super(parent, modal);
        this.janelaPrincipal = janelaPrincipal;
        this.tipoPesquisa = objetoPesquisa;
        this.campoRegistroSelecionado = campoRegistroSelecionado;
        
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtFilter = new javax.swing.JTextField();
        btConcluir = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbPesquisa = new javax.swing.JTable();
        btFilter = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Pesquisar");
        setResizable(false);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btPesquisar.png"))); // NOI18N

        jLabel2.setText("Nome:");

        btConcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btConcluir.png"))); // NOI18N
        btConcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConcluirActionPerformed(evt);
            }
        });

        btCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btCancelar.png"))); // NOI18N
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        tbPesquisa.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Nome"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbPesquisa);

        btFilter.setText("Filtrar");
        btFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFilterActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtFilter, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btFilter))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(txtFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btFilter))
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Limpa os registros presentes na tabela.
     */
    public void limparTabela()
    {
        DefaultTableModel dtm = (DefaultTableModel)this.tbPesquisa.getModel();
        while(dtm.getRowCount() > 0)
        {
            dtm.removeRow(0);
        }
    }
    
    /**
     * Filtrar objetos e apresentalos na tabela. Será filtrado o objeto correspondente ao passado
     * <br>na instância desta classe e buscado na lista presente no Armazem.
     * 
     * @param filter Informar um filtro para selecionar os registros. Se o filtro for <code>""</code>,
     * <br>não será feita a filtragem.
     */
    public void pesquisar(String filter)
    {
        DefaultTableModel dtm = (DefaultTableModel)this.tbPesquisa.getModel();
        this.limparTabela();

        if(tipoPesquisa.equals("Item"))
        {
            for(Item in : this.janelaPrincipal.getArmazem().getListaItens())
            {
                if(!filter.equals("") && !filter.equals(in.getNome()))
                {
                    continue;
                }
                dtm.addRow(new Object[]{in.getId(),in.getNome()});
            }
        }
        if(tipoPesquisa.equals("Cliente"))
        {
            for(Cliente in : this.janelaPrincipal.getArmazem().getListaClientes())
            {
                if(!filter.equals("") && !filter.equals(in.getNome()))
                {
                    continue;
                }
                dtm.addRow(new Object[]{in.getId(),in.getNome()});
            }
        }
    }
    
    /**
     * Verificar registro selecionado na tabela e adicionar valor do ID no campo
     * <br>passado como parâmetro na instância desta classe.
     * 
     * @param evt Não Utilizado.
     */
    private void btConcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConcluirActionPerformed

        if(this.tbPesquisa.getSelectedRow() != -1)
        {
            this.campoRegistroSelecionado.setText(this.tbPesquisa.getValueAt(this.tbPesquisa.getSelectedRow(), 0) + "");
            this.dispose();
            return;
        }
        JOptionPane.showMessageDialog(this, "Nenhum registro selecionado", "Informação", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_btConcluirActionPerformed

    /**
     * Fechar janela.
     * 
     * @param evt Não Utilizado.
     */
    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed

        this.dispose();

    }//GEN-LAST:event_btCancelarActionPerformed

    /**
     * Se caso havar um filtro informado será apresentado na tabela somente os objetos
     * <br>que tenham o nome correspondente ao filtro.
     * 
     * @param evt Não Utilizado
     */
    private void btFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFilterActionPerformed
        this.pesquisar(this.txtFilter.getText());
    }//GEN-LAST:event_btFilterActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btConcluir;
    private javax.swing.JButton btFilter;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbPesquisa;
    private javax.swing.JTextField txtFilter;
    // End of variables declaration//GEN-END:variables
}
